﻿using GlobalData;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Model.Core.Entity.Dbcontexts;
using Model.Core.Services;
using System.IO;
using System.Windows;

namespace RobotPratolSolution
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {

        public static IServiceProvider ServiceProvider { get; private set; }
        public static string RobotId { get; private set; }
        public App()
        {

            IServiceCollection serviceDescriptors = new ServiceCollection();
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configures/cloudmqttclient.json"), true, true);
            builder.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configures/localmqttclient.json"), true, true);
            builder.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configures/robotbase.json"), true, true);
            builder.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configures/database.json"), true, true);
            builder.AddJsonFile(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configures/navinfo.json"), true, true);

            IConfiguration configuration = builder.Build();
            serviceDescriptors.AddSingleton<IConfiguration>(configuration);

            serviceDescriptors.AddDbContext<DbcontextBase>(options =>
            {
                options.UseMySql(
                    connectionString: configuration.GetConnectionString("ConnectionString"),
                    serverVersion: new MySqlServerVersion(new Version(8, 2, 0))
                    )
                    .UseLoggerFactory(LoggerFactory.Create(builder =>
                    {
                        builder.AddConsole().SetMinimumLevel(LogLevel.Warning);
                    }));
            });
            serviceDescriptors.AddLogging(loggingBuilder => { loggingBuilder.AddConsole(); });
            serviceDescriptors.AddSingleton<LocalRobotInfo>();
            serviceDescriptors.AddSingleton<CloudMqClientCtrl>();
            serviceDescriptors.AddSingleton<MqTopics>();
            ServiceProvider = serviceDescriptors.BuildServiceProvider();
            RobotId = configuration.GetSection("RobotInfos:RobotId").Value;
        }
    }

}
